package com.jing21.learn.fs.util;

import com.aliyuncs.DefaultAcsClient;
import org.jglue.fluentjson.JsonBuilderFactory;

import javax.inject.Inject;
import javax.inject.Named;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * Policy 生成工具
 * Create By zhengjing on 2017/11/8 09:20
 */
@Named("policyUtilly")
public class PolicyUtilly {

    public static final String STATIC_BUKET_NAME = "jing21-static";
    @Inject
    DefaultAcsClient acsClient;

    /**
     * 获取 static 读取的数据
     * @param path 路径
     * @return
     */
    public String staticRead(String path) {

        return read(STATIC_BUKET_NAME,path);
    }

    public String read(String bucketName, String path){

        String osspath = bucketName + (path.startsWith("/") ? path : "/" + path);
        //生成只读 权限 授权5分钟
        return JsonBuilderFactory.buildObject()
                .add("Version", "1")
                .addArray("Statement")
                    .addObject()
                        .add("Effect","Allow")
                        .addArray("Action")
                            .add("oss:List*").add("oss:Get*").end()
                        .addArray("Resource")
                            .add("acs:oss:*:*:"+bucketName).add("acs:oss:*:*:"+ osspath).end()
                        .addObject("Condition")
                            .addObject("DateLessThan")
                                .add("acs:CurrentTime", LocalDateTime.now().plus(5, ChronoUnit.MINUTES).toString())
                            .end()
                        .end()
                .end()
                .toString();

    }

    /**
     * 上传权限
     * @param bucketName 块名
     * @param path 路径
     * @return
     */
    public String write(String bucketName,String path){

        String osspath = bucketName + (path.startsWith("/") ? path : "/" + path);
        //生成只读 权限 授权5分钟
        return JsonBuilderFactory.buildObject()
                .add("Version",1)
                .addArray("Statement")
                    .addObject()
                        .add("Effect","Allow")
                        .addArray("Action")
                            .add("oss:*").end()//好大的权限
                        .addArray("Resource")
                            .add("acs:oss:*:*:"+bucketName).add("acs:oss:*:*:"+ osspath).end()
                        .addObject("Condition")
                            .addObject("acs:CurrentTime")
                                .add("DateLessThan", LocalDateTime.now().plus(5, ChronoUnit.MINUTES).toString())
                            .end()
                        .end()
                .end()
                .toString();

    }

}
